package kin.controller.system;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import kin.annotation.system.Module;
import kin.bean.security.Acl;
import kin.bean.security.User;
import kin.context.system.SessionContext;
import kin.manager.security.AclManager;
import kin.manager.security.RoleManager;
import kin.service.security.AclServiceManager;
import kin.service.security.ModuleServiceManager;
import kin.service.security.RoleServiceManager;
import kin.service.security.UserServiceManager;
import kin.system.security.MyInvocationSecurityMetadataSourceService;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
@Module(label = "nav.role.controller",
renderToNAV = true)

public class UserController extends BaseController {

	/*
	 * @Inject AuthenticationManager authenticationManager;
	 */

	@Inject
	private RoleServiceManager roleServiceManager;

	@Inject
	private AclServiceManager aclServiceManager;
	private String rand;

	@Inject
	private UserServiceManager userServiceManager;

	@Inject
	private ModuleServiceManager moduleServiceManager;

	@ResponseBody
	@Module(label = "nav.role.list", renderToNAV = true)
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Object list() {
		List l = null;
		try {
			l = this.userServiceManager.findAll();
			getResult().setObject(l);
		} catch (Exception e1) {
			getResult().setSuccess(Boolean.valueOf(false));
		}

		return getResult();
	}

	public Object usernameIsExist() {
		return null;
	}

	@ResponseBody
	@RequestMapping(value = { "/add" }, method = RequestMethod.POST)
	public Object add(User user, HttpSession s) {
		try {
			this.userServiceManager.add(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return getResult();
	}

	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Object login(HttpServletRequest request, String username,
			String password, HttpSession session) throws Exception {
		UserDetails userDetails = this.userServiceManager
				.loadUserByUsername(username);
		if (userDetails == null || !userDetails.getPassword().equals(password)) {
			this.getResult().setMessage("用户名或密码错误!");
			this.getResult().setSuccess(false);
			return this.getResult();

		} else {
			if (userDetails.getAuthorities() == null
					|| userDetails.getAuthorities().size() == 0) {
				this.getResult().setSuccess(false);
				this.getResult().setMessage("该用户没有分配权限,请与管理员联系!");
				return this.getResult();
			}
			Authentication authentication = new UsernamePasswordAuthenticationToken(
					userDetails, userDetails.getPassword(),
					userDetails.getAuthorities());
			this.getResult().setSuccess(true);

			System.out.println("authentication.getPrincipal():"
					+ authentication.getPrincipal());
			SecurityContext securityContext = SecurityContextHolder
					.getContext();

			securityContext.setAuthentication(authentication);

			Set<String> mc = new HashSet<String>();
			String role = SecurityContextHolder.getContext()
					.getAuthentication().getPrincipal().toString();
			for (GrantedAuthority authority : securityContext
					.getAuthentication().getAuthorities()) {
				if (authority.getAuthority() != null) {
					role = authority.getAuthority();
				}
			}
			Map<String, Collection<ConfigAttribute>> resourceMap = MyInvocationSecurityMetadataSourceService
					.getResourceMap();
			for (Map.Entry<String, Collection<ConfigAttribute>> entry : resourceMap
					.entrySet()) {
				String key = entry.getKey();

				Collection<ConfigAttribute> cs = resourceMap.get(key);
				for (ConfigAttribute c : cs) {
					System.out.println("c.getAttribute():" + c.getAttribute());
					if (c.getAttribute().equals(role)) {

						if (!mc.contains(key)) {
							mc.add(key);
						}
					}
				}

			}
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			user = this.userServiceManager.login(user);
			List l = this.moduleServiceManager.findParentModuleByRole(mc);
			session.setAttribute("language", "en");
			SessionContext.addSessoin(
					session,
					l,
					this.aclServiceManager.findByUser(Acl.TYPE_ROLE,
							user.getUser_id()));
			this.getResult().setMessage("登录成功!");
			/*
			 * HttpSession session = request.getSession(true);
			 * session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
			 */
		}
		return this.getResult();
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public Object login() throws Exception {

		return "/ext/login";
	}

	@RequestMapping({ "/error" })
	public Object login1() throws Exception {
		return "error";
	}

	public Object findRolesByUser() throws Exception {
		return null;
	}

	public String showAddRolesByUserId() throws Exception {
		return null;
	}

	public Object addOrUpdateUsersRoles() throws Exception {
		return null;
	}

	public String deleteUsersRoles() throws Exception {
		return null;
	}

	public String getRand() {
		return this.rand;
	}

	public void setRand(String rand) {
		this.rand = rand;
	}

	public UserServiceManager getUserServiceManager() {
		return this.userServiceManager;
	}

	public void setUserServiceManager(UserServiceManager userServiceManager) {
		this.userServiceManager = userServiceManager;
	}

	public RoleServiceManager getRoleServiceManager() {
		return roleServiceManager;
	}

	public void setRoleServiceManager(RoleServiceManager roleServiceManager) {
		this.roleServiceManager = roleServiceManager;
	}

	public AclServiceManager getAclServiceManager() {
		return aclServiceManager;
	}

	public void setAclServiceManager(AclServiceManager aclServiceManager) {
		this.aclServiceManager = aclServiceManager;
	}

	public ModuleServiceManager getModuleServiceManager() {
		return moduleServiceManager;
	}

	public void setModuleServiceManager(
			ModuleServiceManager moduleServiceManager) {
		this.moduleServiceManager = moduleServiceManager;
	}

	/*
	 * @ResponseBody
	 * 
	 * @Module(label="delete User",renderToNAV=true)
	 * 
	 * @RequestMapping(value="/delete", method=RequestMethod.DELETE) public
	 * Object delete() {
	 * 
	 * return null; }
	 */

	/*
	 * public AuthenticationManager getAuthenticationManager() { return
	 * this.authenticationManager; }
	 * 
	 * public void setAuthenticationManager(AuthenticationManager
	 * authenticationManager) { this.authenticationManager =
	 * authenticationManager; }
	 */
}